// https://leetcode.cn/problems/combination-sum-ii/

/*
给定一个候选人编号的集合 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次 。

注意：解集不能包含重复的组合。 
*/
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    int len = 0;
    vector <vector<int>> res;

    vector <vector<int>> combinationSum2(vector<int> &candidates, int target) {
        sort(candidates.begin(), candidates.end());
//        for (auto item : candidates) {
//            cout << item << ",";
//        }
//        cout << endl;

        len = candidates.size();
        vector<int> combine = {};
//		dfs(res, candidates, combine, len, target, 0, 0);
        dfs1(candidates, target, combine, 0, 0);
        return res;
    }

    void dfs(vector <vector<int>> &res, vector<int> &candidates, vector<int> combine, int len, int target, int num,
             int offset) {
        for (int i = offset; i < len; i++) {
            num += candidates[i];
            if (num <= target) {
                combine.push_back(candidates[i]);
                if (num == target) {
                    res.push_back(combine);
                }
                dfs(res, candidates, combine, len, target, num, i + 1);
                combine.pop_back();
                num -= candidates[i];
            } else {
                break;
            }
            // 这里是关键所在
            while (candidates[i] == candidates[i + 1]) {
                i++;
            }
        }
    }

    void dfs1(vector<int> &candidates, int target, vector<int> &tmp, int total, int index) {
        if (total == target) {
            res.push_back(tmp);
            return;
        }
        for (int i = index; i < len; i++) {
            if (total + candidates[i] > target) break;
            tmp.push_back(candidates[i]);
            dfs1(candidates, target, tmp, total + candidates[i], i + 1);
            tmp.pop_back();
            while (i < len - 1 && candidates[i] == candidates[i + 1]) {
                i++;
            }
        }
    }
};

int main() {
    Solution so;
    vector<int> candidates = {10, 1, 2, 7, 6, 1, 5};
    int target = 8;
    vector <vector<int>> res = so.combinationSum2(candidates, target);
    for (auto items : res) {
        for (auto item : items) {
            cout << item << ",";
        }
        cout << endl;
    }
    return 0;
}